package com.message.queue.rabbit.confirms;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 手动消息确实实现类
 * Created by zhangbo on 2020/7/17.
 */
@Component
public class MyAckReceiver implements ChannelAwareMessageListener {


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            /*如监控多个不同业务队列需要处理成不同逻辑时，可通过队列来区分*/
            String consumerQueue = message.getMessageProperties().getConsumerQueue();
            String msg = new String(message.getBody());

            System.out.println("消息来源队列：" + consumerQueue +",消息内容：" + msg);

            if(ThreadLocalRandom.current().nextInt(2) % 2 == 0) {
                System.out.println("message:" + msg + "消费成功");
                /*multiple:true:表示消息全部收到(如果前面有失败的，也不重消费了)，false:如果前端有失败的，则下次会要求继续消费失败的*/
                channel.basicAck(deliveryTag,false);
                return;
            }
            System.out.println("message:" + msg + "消费失败");
        } catch (Exception e) {
            /*requeue为true则重新放回队列，false则抛弃(放到列信队列)*/
            channel.basicReject(deliveryTag,true);
        }
    }

}
